<?php

namespace app\common\library;

use Exception;
use GuzzleHttp\Client;
use support\Log;

class Curl
{
    /**
     * 发送post请求
     * @param $url
     * @param array $data
     * @param string $requestType
     * @param string $log
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function post($url, array $data = [], string $requestType = 'form', string $log = 'gii', $timeout = 0)
    {
        try {
            switch ($requestType) {
                case 'form':
                    $reqData = ['form_params' => $data];
                    break;
                default:
                    $reqData = ['json' => $data];
            }
            if ($timeout > 0) {
                $reqData['timeout'] = $timeout;
            }
            $res = (new Client())->post($url, $reqData);
            if ($res->getStatusCode() != 200) {
                throw new Exception('请求异常，httpCode=' . $res->getStatusCode());
            }
            $result = $res->getBody()->getContents();
            if ($log) {
                Log::channel($log)->info('请求' . $url . '的结果:'.$result);
            }
            $result = json_decode($result, true);
            return Show::success($result);
        } catch (\Exception $e){
            return Show::error($e->getMessage());
        }
    }

    /**
     * 发送get请求
     * @param $url
     * @param array $data
     * @param string $log
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function get($url, array $data = [], string $log = 'gii', $headers = [])
    {
        try {
            $url = $url . http_build_query($data);
            $res = (new Client())->get($url, ['headers' => $headers]);
            if ($res->getStatusCode() != 200) {
                throw new Exception('请求异常，httpCode=' . $res->getStatusCode());
            }
            $result = $res->getBody()->getContents();
            if ($log) {
                Log::channel($log)->info('请求' . $url . '的结果:'.$result);
            }
            $result = json_decode($result, true);
            return Show::success($result);
        } catch (\Throwable $e){
            return Show::error($e->getMessage());
        }
    }
}